<template>
  <DetailsFormBox :isPup="isPup" title="生产单工单" :type="data.type" isFull :form="data.form" :btns="[
    {
      title: '重置',
      icon: '',
      type: '',
      hidden: isFotmDisabled,
      click: getForm,
    },
    {
      title: '仅保存',
      icon: '',
      type: 'primary',
      hidden: isFotmDisabled,
      click: (form: any) => {
        saveBtn(form, false)
      },
    },
    {
      title: '保存并确认',
      icon: '',
      type: 'primary',
      hidden: isFotmDisabled,
      click: (form: any) => {
        saveBtn(form, true)
      },
    },
    {
      title: '外发确认',
      icon: '',
      type: 'primary',
      hidden: isFotmDisabled,
      click: (form: any) => {
        saveSureProduceTaskBill(form)
      },
    },
    {
      title: '更改生产',
      icon: '',
      type: '',
      permission: 'MenuCode2-1-2',
      hidden: !isFotmDisabled || isEdit || data.form?.baseData?.produceBillState === 2,
      isNotRule: true,
      click: (form: any) => {
        isEdit = true
      },
    },
    {
      title: '取消',
      icon: '',
      type: '',
      permission: 'MenuCode2-1-2',
      hidden: !isFotmDisabled || !isEdit,
      isNotRule: true,
      click: (form: any) => {
        isEdit = false
      },
    },
    {
      title: '保存',
      icon: '',
      type: 'primary',
      permission: 'MenuCode2-1-2',
      hidden: !isFotmDisabled || !isEdit,
      isNotRule: true,
      click: (form: any) => {
        saveBtn(form)
      },
    },
  ]" :loading="data.loading" :loadingMsg="data.loadingMsg">
    <template #default="{ form }">
      <MainBox :margin="0" :widthLeft="300" :widthRight="300">
        <template #left>
          <div class="dlText-80 list-b-8 p-12">
            <h3>订单信息</h3>
            <div class="list-b-4">
              <dl>
                <dt>订单单号</dt>
                <dd>
                  <CopyText :data="form?.orderBaseData?.saleOrderGroupNumber" />
                </dd>
              </dl>
              <dl>
                <dt>协议书号</dt>
                <dd>
                  <CopyText :data="form?.baseData?.xieYiShuHao" />
                </dd>
              </dl>
              <dl>
                <dt>客户名称</dt>
                <dd>
                  <CopyText :data="form?.baseData?.customerName" />
                </dd>
              </dl>
              <dl>
                <dt>客户单号</dt>
                <dd>{{ form?.orderBaseData?.customerBillNo || '--' }}</dd>
              </dl>
              <dl>
                <dt>合同号</dt>
                <dd>{{ form?.orderBaseData?.contractCode || '--' }}</dd>
              </dl>
              <dl>
                <dt>下单套量</dt>
                <dd>{{ form?.orderBaseData?.taoZhuangQuantity || 0 }}{{ form?.productInfo?.baseData?.productUnit || ''
                }}
                </dd>
              </dl>
              <dl>
                <dt>下单枚量</dt>
                <dd>{{
                  proxy.$count(`${form?.orderBaseData?.taoZhuangQuantity ||
                    0}*${form?.productInfo?.baseData?.productTagNumber
                    || 0}`)
                  || 0 }}枚</dd>
              </dl>
              <dl>
                <dt>交货日期</dt>
                <dd class="list-r-6">
                  <span>{{ proxy.$day(form?.orderBaseData?.deliveryDate) }}</span>
                  <el-tag
                    :type="proxy.$getDaysUntilDeadline(form?.orderBaseData?.deliveryDate).dayDiff >= 0 ? 'success' : 'danger'"
                    effect="dark" size='small' v-if="form?.baseData?.taskProduceState < 3">
                    {{ proxy.$getDaysUntilDeadline(form?.orderBaseData?.deliveryDate).dayDiffText }}
                  </el-tag>
                </dd>
              </dl>
            </div>
            <el-divider />
            <h3>产品信息</h3>
            <div class="list-b-4">
              <dl>
                <dt>产品名称</dt>
                <dd>
                  <CopyText :data="form?.productInfo?.baseData?.productName" />
                </dd>
              </dl>
              <dl>
                <dt>产品类型</dt>
                <dd>{{ form?.productInfo?.baseData?.productTypeName || '--' }}</dd>
              </dl>
              <dl>
                <dt>产品编码</dt>
                <dd>
                  <CopyText :data="form?.productInfo?.baseData?.productNumber" />
                </dd>
              </dl>
              <dl>
                <dt>产品版本</dt>
                <dd>{{ form?.baseData?.orderProductVersion || '--' }}</dd>
              </dl>
              <dl>
                <dt>产品单位</dt>
                <dd>{{ form?.productInfo?.baseData?.productUnit || '--' }}</dd>
              </dl>
              <dl>
                <dt>产品枚数</dt>
                <dd>{{ form?.productInfo?.baseData?.productTagNumber || '--' }}枚</dd>
              </dl>
              <dl>
                <dt>客户库存</dt>
                <dd class="flex-between-center text-color-error">
                  <span>{{ form?.stockQuantity || 0 }}{{ form?.productInfo?.baseData?.productUnit || ''
                  }}</span>
                  <el-tooltip effect="dark" content="当前库存总数量减去除本身以外的客户待发货总数量" placement="top">
                    <el-icon>
                      <Warning />
                    </el-icon>
                  </el-tooltip>
                </dd>
              </dl>
              <dl>
                <dt>实际库存</dt>
                <dd class="flex-between-center">
                  <span>{{ proxy.$arrTotal(options.productStock, 'stockQuantity') }}{{
                    form?.productInfo?.baseData?.productUnit || ''
                  }}</span>
                  <PopoverTabel :width="600" :thead="[
                    {
                      label: '规格型号',
                      prop: 'productSpecificationName',
                      align: 'center',
                      width: null,
                    },
                    {
                      label: '库区库位',
                      prop: 'wareArea',
                      align: 'center',
                      width: null,
                    },
                    {
                      label: '库存数量',
                      prop: 'stockQuantity',
                      align: 'center',
                      width: null,
                    },
                  ]" :tbody="options.productStock" />
                </dd>
              </dl>
            </div>
            <el-divider />
            <h3>数据信息</h3>
            <div class="list-b-4">
              <dl>
                <dt>数据来源</dt>
                <dd>{{ form?.orderBaseData?.dataComeFromName || '--' }}</dd>
              </dl>
              <dl>
                <dt>数据数量</dt>
                <dd>{{ form?.orderBaseData?.tagDataQuantity || '--' }}</dd>
              </dl>
              <dl>
                <dt>数据状态</dt>
                <dd>{{ form?.orderBaseData?.dataProduceState || '--' }}</dd>
              </dl>
            </div>
            <el-divider />
            <h3>相关人员</h3>
            <div class="list-b-4">
              <dl>
                <dt>业务员</dt>
                <dd>{{ form?.orderBaseData?.salesmanName || '--' }}</dd>
              </dl>
              <dl>
                <dt>开单人</dt>
                <dd>{{ form?.baseData?.createPersonName || '--' }}</dd>
              </dl>
            </div>
            <el-divider />
            <h3>单据信息</h3>
            <div class="list-b-4">
              <dl>
                <dt>单据状态</dt>
                <dd>{{ form?.baseData?.produceBillStateName || '--' }}</dd>
              </dl>
              <dl>
                <dt>开单时间</dt>
                <dd>{{ form?.baseData?.createDate || '--' }}</dd>
              </dl>
            </div>
          </div>
        </template>
        <template #right>
          <div class="list-b-8 p-12">
            <h3>产品要求</h3>
            <CopyText :data="form?.productInfo?.baseData?.productRequirement" placeholder="暂无产品要求" />
            <el-divider />
            <h3>订单备注</h3>
            <CopyText :data="form?.orderBaseData?.orderRemark" placeholder="暂无订单备注" />
            <el-divider />
            <h3>生产备注</h3>
            <CopyText :data="form?.baseData?.produceRemark" placeholder="暂无生产备注" />
            <el-divider />
            <h3>刀模信息</h3>
            <CopyText :data="form?.baseData?.knifeInformation" placeholder="暂无刀模备注" />
            <el-divider />
            <h3>丝网版信息</h3>
            <CopyText :data="form?.baseData?.plateInformation" placeholder="暂无拼板备注" />
          </div>
        </template>
        <template #mainHead>
          <ElRadioBox :data="data" dataName="mainPage" isButton :options="[
            {
              label: '生产信息',
              value: 1
            },
            {
              label: '标签信息',
              value: 2
            }
          ]"></ElRadioBox>
        </template>
        <template #default>
          <template v-if="data.mainPage === 1">
            <CellBox title="生产型号明细" isTop>
              <TableBoxMx :data="{
                tbody: options.orderList,
                thead: [
                  {
                    label: '型号名称',
                    prop: 'productSpecificationName',
                    align: 'center',
                    width: 200,
                  },
                  {
                    label: '生产数量',
                    prop: 'productionQuantity',
                    align: 'center',
                    width: 100,
                  },
                  {
                    label: '已发货数量',
                    prop: 'deliveredQuantity',
                    align: 'center',
                    width: 100,
                  },
                  {
                    label: '备注',
                    prop: 'remark',
                    align: 'left',
                    width: null, // 如果宽度为null，则可能需要根据实际情况调整或留空
                  }
                ]
              }"></TableBoxMx>
            </CellBox>
            <CellBox title="生产信息" isTop>
              <FlexBox :list="3" :margin="2" class="dlText-80">
                <dl>
                  <dt>生产单号</dt>
                  <dd>
                    <CopyText :data="form?.baseData?.produceTaskBillNo" />
                  </dd>
                </dl>
                <dl>
                  <dt>生产类型</dt>
                  <dd>
                    <CopyText :data="form?.baseData?.produceBillTypeName" />
                  </dd>
                </dl>
                <dl>
                  <dt>生产版面</dt>
                  <dd>
                    <CopyText :data="form?.baseData?.printingSurface" />
                  </dd>
                </dl>
                <dl>
                  <dt>生产状态</dt>
                  <dd>
                    <CopyText :data="form?.baseData?.taskProduceState" :options="proxy.$optionsArr.taskProduceState" />
                  </dd>
                </dl>
                <dl>
                  <dt>生产方式</dt>
                  <dd>
                    <CopyText :data="form?.productInfo?.baseData?.productionMode"
                      :options="proxy.$optionsArr.productionMode" />
                  </dd>
                </dl>
                <dl>
                  <dt>生产尺寸</dt>
                  <dd>
                    <CopyText :data="form?.productInfo?.baseData?.productionDimensions" :unit="form?.productInfo?.baseData?.productionMode === 2
                      ? 'mm'
                      : 'T'
                      " />
                  </dd>
                </dl>
                <dl>
                  <dt>跳距</dt>
                  <dd>
                    <CopyText :data="form?.productInfo?.baseData?.makeupSkipDistance" unit="mm" />
                  </dd>
                </dl>
                <dl>
                  <dt>间距</dt>
                  <dd>
                    <CopyText :data="form?.productInfo?.baseData?.makeupSpaceBetween" unit="mm" />
                  </dd>
                </dl>
                <dl>
                  <dt>留边尺寸</dt>
                  <dd>
                    <CopyText :data="form?.productInfo?.baseData?.marginSize" unit="mm" />
                  </dd>
                </dl>
                <dl>
                  <dt>印刷拼版</dt>
                  <dd>
                    <CopyText :data="form?.productInfo?.baseData?.makeupPrintingCombine" />
                  </dd>
                </dl>
                <dl>
                  <dt>刀模模数</dt>
                  <dd>
                    <CopyText :data="form?.productInfo?.baseData?.makeupModules" />
                  </dd>
                </dl>
                <dl>
                  <dt>平张断张</dt>
                  <dd>
                    <CopyText :data="form?.productInfo?.baseData?.makeupPzDz" />
                  </dd>
                </dl>
                <dl>
                  <dt>色数</dt>
                  <dd>
                    <CopyText :data="form?.productInfo?.baseData?.makeupColors" />
                  </dd>
                </dl>
                <dl>
                  <dt>每组数量</dt>
                  <dd>
                    <CopyText :data="form?.productInfo?.baseData?.eachGroupQuantity"
                      :unit="form?.productInfo?.baseData?.productUnit" />
                  </dd>
                </dl>
                <dl>
                  <dt>每组高度</dt>
                  <dd>
                    <CopyText :data="form?.productInfo?.baseData?.eachGroupHeight" unit="mm" />
                  </dd>
                </dl>
                <dl>
                  <dt>刀次高度</dt>
                  <dd>
                    <CopyText :data="form?.productInfo?.baseData?.knifeTimes" unit="mm" />
                  </dd>
                </dl>
                <dl>
                  <dt>成品样式</dt>
                  <dd>
                    <CopyText :data="form?.productInfo?.baseData?.productStyle"
                      :options="proxy.$optionsArr.productStyle" />
                  </dd>
                </dl>
                <dl v-if="[2, 3].includes(form?.productInfo?.baseData?.productStyle)">
                  <dt>出标方向</dt>
                  <dd>
                    <CopyText :data="form?.productInfo?.baseData?.outDirection"
                      :options="proxy.$optionsArr.outDirection" />
                  </dd>
                </dl>
                <template v-if="[2].includes(form?.productInfo?.baseData?.productStyle)">
                  <dl>
                    <dt>卷向</dt>
                    <dd>
                      <CopyText :data="form?.productInfo?.baseData?.scrollDirection"
                        :options="proxy.$optionsArr.scrollDirection" />
                    </dd>
                  </dl>
                  <dl>
                    <dt>卷芯大小</dt>
                    <dd>
                      <CopyText :data="form?.productInfo?.baseData?.mandrelSize" unit="mm" />
                    </dd>
                  </dl>
                  <dl>
                    <dt>最大外直径</dt>
                    <dd>
                      <CopyText :data="form?.productInfo?.baseData?.notOverDiameter" unit="mm" />
                    </dd>
                  </dl>
                </template>
                <dl>
                  <dt>贴标方式</dt>
                  <dd>
                    <CopyText :data="form?.productInfo?.baseData?.tagAffixWay"
                      :options="proxy.$optionsArr.tagAffixWay" />
                  </dd>
                </dl>
                <dl>
                  <dt>{{ `每${[1, 3].includes(form?.productInfo?.baseData?.productStyle)
                    ? "张"
                    : "卷"}${form?.productInfo?.baseData?.productUnit || '枚'}数` }}</dt>
                  <dd>
                    <CopyText :data="form?.productInfo?.baseData?.pageEqualTags"
                      :unit="form?.productInfo?.baseData?.productUnit" />
                  </dd>
                </dl>
                <dl v-if="[1, 3].includes(form?.productInfo?.baseData?.productStyle)">
                  <dt>每包张数：</dt>
                  <dd>
                    <CopyText :data="form?.productInfo?.baseData?.packageEqualPages" unit="张" />
                  </dd>
                </dl>
              </FlexBox>
            </CellBox>
            <CellBox title="" isTop>
              <FlexBox :list="3" :marign="8">
                <ElFormItemBox label="生产数量" :prop="`baseData.productionQuantity`" isRules>
                  <ElInputBox :data="form.baseData" dataName="productionQuantity"
                    :unit="form?.productInfo?.baseData?.productUnit" :disabled="isFotmDisabled" />
                </ElFormItemBox>
                <ElFormItemBox label="打印用料" :prop="`baseData.printingMaterials`" isRules>
                  <ElInputBox :data="form.baseData" dataName="printingMaterials" unit="米" :disabled="isFotmDisabled" />
                </ElFormItemBox>
                <ElFormItemBox label="计划用料" :prop="`baseData.plannedMaterials`" isRules>
                  <ElInputBox :data="form.baseData" dataName="plannedMaterials" unit="米" :disabled="isFotmDisabled" />
                </ElFormItemBox>
                <ElFormItemBox label="到料情况">
                  <ElInputBox :data="form.baseData" dataName="materialArrival" unit="米" :disabled="isFotmDisabled" />
                </ElFormItemBox>
                <ElFormItemBox label="刀模信息" :prop="`knifeInformation`">
                  <ElInputBox :data="form.baseData" dataName="knifeInformation" disabled />
                  <template #btn v-if="!isFotmDisabled">
                    <el-button @click="() => {
                      form.baseData.knifeInformation = ''
                      form.baseData.knifeVersionCode = ''
                    }" v-if="form.baseData.knifeVersionCode">清除</el-button>
                    <SelectEditionAdminKnifeMold @selectBtn="(arr: any) => {
                      form.baseData.knifeInformation = `${arr[0].knifeVersionNo}${arr[0].knifeVersionName}`
                      form.baseData.knifeVersionCode = arr[0].knifeVersionCode
                    }" />
                  </template>
                </ElFormItemBox>
                <ElFormItemBox label="丝网版信息">
                  <ElInputBox :data="form.baseData" dataName="plateInformation" :disabled="isFotmDisabled" />
                </ElFormItemBox>
                <ElFormItemBox label="生产备注" class="wAuto">
                  <ElInputBox :data="form.baseData" dataName="produceRemark" type="textarea"
                    :disabled="isFotmDisabled" />
                </ElFormItemBox>
              </FlexBox>
            </CellBox>
            <CellBox title="彩稿信息" isTop>
              <ElImgListBox :data="form?.productInfo?.productColorDraftFileList" urlKey="draftFileUrl" />
            </CellBox>
            <CellBox title="颜色信息" isTop>
              <TableBoxMx :data="{
                disabled: isFotmDisabled && !isEdit,
                tbody: form.colorMachineList,
                thead: [
                  {
                    label: '颜色名称',
                    prop: 'colorName',
                    align: 'center',
                    width: 200,
                  },
                  {
                    label: '参考',
                    prop: 'colorReference',
                    align: 'center',
                    width: 100,
                    options: proxy.$optionsArr.colorType,
                  },
                  {
                    label: '使用设备',
                    prop: 'machineCode',
                    align: 'center',
                    width: 140,
                    formType: 'select', //文件类型
                    options: options.machine,
                  },
                  {
                    label: '备注',
                    prop: 'colorRemark',
                    align: 'left', // 根据您的描述设置为左对齐
                    width: null, // 如果宽度未指定，则设为null或根据实际情况调整
                  }
                ]
              }"></TableBoxMx>
            </CellBox>
            <CellBox title="生产工艺" isTop>
              <template #btn v-if="!isFotmDisabled">
                <el-link icon="Refresh" @click="refreshBtn('工艺')">重置工艺</el-link>
              </template>
              <TableBoxMx :data="{
                tableId: 'productionModel',
                disabled: isFotmDisabled && !isEdit,
                tbody: form.produceCraftList,
                thead: [
                  {
                    label: '工艺编号',
                    prop: 'produceCraftNo',
                    align: 'center',
                    width: 90,
                  },
                  {
                    label: '工艺名称',
                    prop: 'produceCraftNo',
                    align: 'left',
                    width: 220,
                    formType: 'select', //文件类型
                    formProp: `produceCraftList`,//必填
                    options: options.produceCraft,
                    changeBtn: (value: string, item: any, row: any) => {
                      proxy.$api.ProductionBusniess.SureChooseProduceCraftEquipmentMaps({
                        craftCodes: [value]
                      })
                        .then((res: any) => {
                          item.produceCraftName = row[0].label
                          item.produceEquipment = ''
                          item.produceEquipmentName = ''
                          if (res.length > 0) {
                            const _craftEquipments = res[0].craftEquipments
                            item.craftEquipments = _craftEquipments
                            if (_craftEquipments.length === 0) {
                              item.produceCraftName = ''
                              item.produceCraftNo = ''
                              proxy.$message('该工艺未关联设备，请先添加', 'error')
                            } else {
                              item.produceEquipmentName = _craftEquipments[0].equipmentName
                              item.produceEquipment = _craftEquipments[0].equipmentCode
                            }
                          } else {
                            item.craftEquipments = []
                          }
                          tableShowBtn()
                        })
                        .catch(() => { });
                    }
                  },
                  {
                    label: '使用设备',
                    prop: 'produceEquipmentName',
                    align: 'left',
                    width: 120,
                    formType: 'select', //文件类型
                    optionsRow: 'craftEquipments',
                    formProp: `produceCraftList`,//必填
                    labelName: 'equipmentName',
                    valueName: 'equipmentCode',
                    changeBtn: (value: string, item: any, row: any) => {
                      item.produceEquipmentName = row[0].equipmentName
                      item.produceEquipment = row[0].equipmentCode
                      tableShowBtn()
                    }
                  },
                  {
                    label: '计划工时',
                    prop: 'craftTaskPlanUseTime',
                    align: 'center',
                    width: 100,
                    formType: 'number', //文件类型
                  },
                  {
                    label: '标准效率',
                    prop: 'standardEfficiency',
                    align: 'center',
                    width: 120
                  },
                  {
                    label: '工艺状态',
                    prop: 'craftTaskState',
                    align: 'center',
                    width: 120,
                    isTag: true, //文件类型
                    options: proxy.$optionsArr.craftTaskState,
                  },
                  {
                    label: '备注',
                    prop: 'craftTaskRemark',
                    align: 'center',
                    formType: 'text', //文件类型
                  }
                ],
                //排序key
                sortKey: 'produceCraftSort',
                sortTitle: (row: any) => {
                  return `${row.produceCraftName}-${row.produceEquipmentName}`
                },
                //操作
                operation: [
                  {
                    label: '复制',
                    icon: 'CopyDocument',
                    notArr: ['craftTaskID', 'produceCraftNo', 'produceEquipment', 'craftTaskPlanUseTime', 'craftTaskNo', 'craftTaskRemark']
                  },
                  {
                    label: '删除',
                    icon: 'Delete'
                  }
                ],
                add: {
                  craftEquipments: [],
                  craftTaskNo: '', //工艺任务单号
                  craftTaskClientNo: '', //生产工艺任务前端唯一识别码
                  produceCraftNo: '', //生产工艺代码
                  produceEquipment: '', //生产设备代码
                  productTechniqueCode: '', //产品工艺配置编码
                  craftTaskPlanUseTime: 0, //工艺任务计划用时，单位：分钟
                  craftTaskRemark: '', //工艺任务备注说明
                  produceCraftSort: 0, //生产工艺排序
                  standardEfficiency: 0, //标准效率（米/小时）
                  craftTaskState: -1 //工艺状态
                }
              }" @onSort="tableShowBtn">
                <template #standardEfficiency="{ row }">
                  {{ setStandardEfficiency(row) }}米/分钟
                </template>
                <template #craftTaskPlanUseTime="{ row, index }" v-if="!isFotmDisabled">
                  <ElFormItemBox>
                    <el-input v-model="row.craftTaskPlanUseTime" type="number"
                      :ref="(el: any) => { if (el) timeRef[`craftTaskPlanUseTime${index}`] = el }" @change="() => {
                        const _length = form?.produceCraftList?.length
                        const _index: number = _length - 1 !== index ? index + 1 : 0
                        const _ref: any = timeRef[`craftTaskPlanUseTime${_index}`]
                        const _plannedMaterials = form?.baseData?.plannedMaterials || 0
                        let _standardEfficiency = _plannedMaterials > 0 && row.craftTaskPlanUseTime ?
                          proxy.$count(`${_plannedMaterials}/${row.craftTaskPlanUseTime || 0}`, 0) : 0
                        row.standardEfficiency = _standardEfficiency
                        _ref?.focus()
                        _ref?.select()
                      }" />
                  </ElFormItemBox>
                </template>
                <template #craftTaskState="{ row, index }"
                  v-if="isFotmDisabled && !isPup && data.form?.baseData?.produceBillState !== 2"
                  :v-permission="`MenuCode2-1-2`">
                  <ElSelectBox :data="row" dataName="craftTaskState" :options="proxy.$optionsArr.craftTaskState"
                    @changeBtn="setCraftTaskState" />
                </template>
              </TableBoxMx>
            </CellBox>
            <CellBox title="生产物料" isTop>
              <template #btn v-if="!isFotmDisabled">
                <el-link icon="Refresh" @click="refreshBtn('物料')">重置物料</el-link>
              </template>
              <GoodList :data="{
                disabled: isFotmDisabled && !isEdit,
                height: 290,
                rowKey: 'stockGoodsCode',
                prop: 'produceMaterialList',
                tbody: form.produceMaterialList,
                thead: [
                  {
                    label: '使用工艺',
                    prop: 'craftTaskClientNo',
                    width: 220,
                    isRules: true,
                    formType: 'select', //文件类型
                    options: form?.produceCraftList?.map((el: any) => ({
                      ...el,
                      label: `${el.produceCraftName}-${el.produceEquipmentName}`,
                      value: el.craftTaskClientNo,
                    })),
                  },
                  {
                    label: '备注',
                    prop: 'produceMaterialRemark',
                    formType: 'textarea'
                  },
                ],
                operation: [
                  {
                    label: '删除',
                    icon: 'Delete',
                  },
                ],
              }" @selectBtn="addMx" v-if="tableShow">
              </GoodList>
            </CellBox>
          </template>
          <template v-else>
            <ProductTag :data="form?.productInfo?.productTagList" />
          </template>
        </template>
      </MainBox>
    </template>
  </DetailsFormBox>
</template>
<script setup lang="ts">
import { sendMsg } from '@/utils/crossTagMag.ts';
import { useListComponent } from '../pageTs'; // 引入逻辑
const { dataInfo } = useListComponent();
const { proxy } = getCurrentInstance() as any;
const props = withDefaults(
  defineProps<{
    isPup?: boolean;//是否弹窗
    query?: any;//参数
  }>(),
  {

  },
);
const timeRef: any = ref({});
const data: any = reactive({
  loading: false,
  loadingMsg: '',
  type: 1,
  mainPage: 1,
  form: {

  },
});
const tableShowBtn = () => {
  tableShow.value = false
  nextTick((el: any) => {
    tableShow.value = true
  })
}
const tableShow = ref(true)
const isFotmDisabled = ref(true)
const isEdit = ref(false)
const options = reactive({
  surfaceRequires: [], //表面要求
  productStock: [], //库存明细
  orderList: [], //库存明细
  machine: [],
  produceCraft: [],
  //印刷版本
  craftTaskState: [
    {
      label: "待生产",
      value: -1,
      type: "info"
    },
    {
      label: "待生产",
      value: 0,
      type: "info"
    },
    {
      label: "生产中",
      value: 1,
      type: ""
    },
    {
      label: "已完成",
      value: 2,
      type: "success"
    }
  ],
  taskProduceState: [
    {
      label: "生产中",
      value: 1
    },
    {
      label: "待停工",
      value: 2
    },
    {
      label: "已停工",
      value: 3
    },
    {
      label: "已完成",
      value: 4
    },
    {
      label: "待生产",
      value: 0
    }
  ], //生产单状态
  craftState: [
    {
      label: "待生产",
      value: -1
    },
    {
      label: "待开始",
      value: 0
    },
    {
      label: "生产中",
      value: 1
    },
    {
      label: "已完成",
      value: 2
    }
  ], //工艺状态
});
import { useRoute } from 'vue-router';
// 获取当前路由对象
const route = useRoute();
//
//添加关联单明细
const addMx = (rows: any) => {
  const _rows = Array.isArray(rows) ? rows : [rows]
  let _arr = _rows.map((el: any) => ({
    craftTaskClientNo: '', // 生产工艺任务前端唯一识别码
    specificationCode: el.specificationCode, // 库存物料代码
    stockGoodsCode: el.specificationCode, // 库存物料代码
    planUseQuantity: '', // 计划用料数量
    printMaterialQuantity: '', // 打印用料数量
    materialRemark: '' // 物料备注
  }))
  data.form.produceMaterialList.push(
    ..._arr
  )
}
//标准效率
const setStandardEfficiency = (row: any) => {
  const _baseData: any = data.form.baseData
  if (!row.craftTaskClientNo && row.produceCraftNo && row.produceEquipment) {
    row.craftTaskClientNo = `${row.produceCraftNo}${row.produceEquipment}`
  }
  if (_baseData?.plannedMaterials && row.craftTaskPlanUseTime) {
    const _standardEfficiency = Math.floor(_baseData.plannedMaterials / row.craftTaskPlanUseTime)
    row.standardEfficiency = _standardEfficiency
    return _standardEfficiency
  } else {
    return ''
  }
}
//重置物料信息
const refreshBtn = (type: string) => {
  let _form: any = data.form
  switch (type) {
    case '物料':
      _form.produceMaterialList = _form.productInfo.productMaterialList.map((el: any) => ({
        goodsName: el.materialName,
        stockGoodsCode: el.specification,
        specificationCode: el.specification,
        specificationName: el.stockGoodsName,
        categoryName: el.materialType,
        produceCraftName: '',
        craftTaskRemark: el.materialRemark,
        stockQuantity: el.stockQuantity,
      }))
      break;
    case '工艺':
      _form.produceCraftList = _form.productInfo.productTechniqueList.map((el: any, index: number) => ({
        craftEquipments: el.produceMachineList.map((row: any) => ({
          equipmentName: row.machineName,
          equipmentCode: row.machineCode,
        })),
        craftTaskNo: '', //工艺任务单号
        craftTaskClientNo: `${el.craftCode}${el.deviceCode}`, //生产工艺任务前端唯一识别码
        produceCraftNo: el.craftCode, //生产工艺代码
        produceCraftName: proxy.$arrFind(proxy.$optionsArr.produceCraft, el.craftCode, 'value', 'label'), //生产工艺代码
        produceEquipment: el.deviceCode, //生产设备代码
        produceEquipmentName: proxy.$arrFind(el.produceMachineList, el.deviceCode, 'machineCode', 'machineName'), //生产设备代码
        productTechniqueCode: '', //产品工艺配置编码
        craftTaskPlanUseTime: 0, //工艺任务计划用时，单位：分钟
        craftTaskRemark: el.craftRequirement, //工艺任务备注说明
        produceCraftSort: index + 1, //生产工艺排序
        standardEfficiency: 0, //标准效率（米/小时）
        craftTaskState: -1, //工艺状态
      }))
      _form.produceMaterialList = _form.produceMaterialList.map((el: any) => ({
        ...el,
        craftTaskClientNo: '',
      }))
      break;

    default:
      break;
  }
  tableShowBtn()
};
//修改生产工艺状态
const setCraftTaskState = (value: any, row: any) => {
  proxy.$api.ProductionBusniess.UpdateProduceCraftTaskState({
    craftTaskNo: row.craftTaskNo,
    craftTaskState: value
  })
    .then((res: any) => {
      proxy.$message('状态修改成功')
      sendMsg('save', true);
    })
    .catch(() => { });
};
//获取数据
const getForm = () => {
  setLoading()
  let _query: any = props.query || route.query
  data.type = _query.type
  proxy.$api.ProductionBusniess.GetProduceTaskBillDetail({
    produceTaskBillNo: _query.produceTaskBillNo,
  })
    .then((res: any) => {
      isFotmDisabled.value = !['1', '2'].includes(_query.type) || res.baseData.produceBillState !== 0 || props.isPup//表单是否可以编辑
      proxy.$message('获取成功')
      data.form = setForm(res)
      getOrderProductSpecificationBySaleOrderCode(res)
      getFinishedProductStockPageList(res) //获取成品库存
      data.loading = false
    })
    .catch(() => {
      data.loading = false
    });
};
const setForm = (res: any) => {
  const _productPrintingColorList = res.productInfo.productPrintingColorList
  const _form = {
    ...res,
    baseData: {
      ...res.baseData,
      printingMaterials: res.baseData.printingMaterials || null,
      plannedMaterials: res.baseData.plannedMaterials || null,
    },
    //颜色信息
    colorMachineList: _productPrintingColorList.map((el: any, index: number) => {
      return {
        produceTaskBillNo: res.baseData.produceTaskBillNo,
        printColorCode: el.colorCode,
        colorName: el.colorName,
        colorRemark: el.colorRemark,
        colorReference: el.colorReference,
        machineCode: res.colorMachineList[index]?.machineCode || '',
      }
    }),
    //生产工艺
    produceCraftList: res.produceCraftList.map((el: any) => {
      const isCraftEquipments = el.craftEquipments.length > 0
      return {
        ...el.produceCraft,
        produceEquipment: isCraftEquipments ? el.produceCraft.produceEquipment : '',
        produceEquipmentName: isCraftEquipments ? el.produceCraft.produceEquipmentName : '',
        craftEquipments: el.craftEquipments
      }
    })
  }
  return _form
};
//根据订单编码获取订单的产品型号数据
const getOrderProductSpecificationBySaleOrderCode = (form: any) => {
  proxy.$api.OrderBusniess.GetOrderProductSpecificationBySaleOrderCode({
    queryBy: 0,
    queryValue: form?.baseData?.saleOrderNo,
    xieYiShuHao: form?.baseData?.xieYiShuHao,
  })
    .then((res: any) => {
      options.orderList = res;
    })
    .catch(() => { });
};
//获取成品明细
const getFinishedProductStockPageList = (form: any) => {
  proxy.$api.FinishedProduct.GetFinishedProductStockPageList({
    pageIndex: 1,
    pageSize: 999,
    queryDataBaseFiled: "productSpecificationNumber",
    likeWords: form.productInfo?.baseData?.productNumber,
    isShowDisabled: 0,
    onlyStocked: 1, // -1：显示全部、0：不显示0库存、1：仅显示0库存
    productNo: ""
  })
    .then((res: any) => {
      options.productStock = proxy.$flattenObjectArray(res.list, 'details', (row: any) => ({
        productSpecificationName: row.productSpecificationName,//成品规格
        wareArea: `${row.wareHouseAreaName}/${row.areaSheltName}`,//仓库
        stockQuantity: row.stockQuantity,//数量
      }))
      console.log(options.productStock);

    })
    .catch(() => { });
};
const saveSureProduceTaskBill = (form: any) => {
  proxy.$messageBox('是否外发，请确认！', () => {
    proxy.$api.ProductionBusniess.SureProduceTaskBill({
      produceTaskID: form.baseData.produceTaskID
    })
      .then((res: any) => {
        proxy.$message('保存成功')
        sendMsg('save', true);
        // getForm();
        window.close();
      })
      .catch(() => { });
  });
};
const saveBtn = (form: any, isConfirm: boolean = false) => {
  const _baseData = form.baseData
  const _productBaseData = form.productInfo.baseData
  const _form = {
    produceTaskID: _baseData.produceTaskID, // 生产任务单编号
    makeup_RollSize: _baseData.productionDimensions, // 版辊尺寸，单位：毫米
    makeup_DigitalEdition: _productBaseData.productionDimensions, // 数码版面，单位：毫米
    produceRemark: _baseData.produceRemark, // 生产备注说明
    planCpMeters: _baseData.planCpMeters, // 计划成品米数
    productionQuantity: _baseData.productionQuantity, // 生产数量
    eachGroupQuantity: _baseData.eachGroupQuantity, // 每组数量
    eachGroupHeight: _baseData.eachGroupHeight, // 每组高度
    theoreticalMaterials: _baseData.theoreticalMaterials, // 理论用料
    printingMaterials: _baseData.printingMaterials, // 打印用料
    plannedMaterials: _baseData.plannedMaterials, // 计划用料
    materialArrival: _baseData.materialArrival, // 到料情况
    metersPerRoll: _baseData.metersPerRoll, // 每卷米数
    knifeInformation: _baseData.knifeInformation, // 刀版唯一编码
    knifeVersionCode: _baseData.knifeVersionCode, // 刀版唯一编码
    plateInformation: _baseData.plateInformation, // 印版信息
    marginSize: _baseData.marginSize, // 留边尺寸
    knifeVersionNo: _baseData.knifeVersionNo, // 刀版编号
    producePackage: form.packageData,
    productTagCodes: form.productInfo.productTagList.map((el: any) => el.productTagCode), // 生产标签代码集合
    produceCrafts: form.produceCraftList.map((el: any) => ({
      craftTaskID: el.craftTaskID, // 生产工艺任务主键ID
      craftTaskNo: el.craftTaskNo, // 生产工艺任务单号（唯一识别码）
      craftTaskClientNo: el.craftTaskClientNo, // 生产工艺任务前端唯一识别码
      produceCraftNo: el.produceCraftNo, // 生产工艺代码
      produceEquipment: el.produceEquipment, // 生产设备代码
      productTechniqueCode: el.productTechniqueCode, // 产品工艺配置编码
      craftTaskPlanUseTime: el.craftTaskPlanUseTime, // 工艺任务计划用时，单位：分钟
      craftTaskRemark: el.craftTaskRemark, // 工艺任务备注说明
      produceCraftSort: el.produceCraftSort, // 生产工艺排序
      standardEfficiency: el.standardEfficiency // 标准效率（米/小时）
    })),
    produceMaterials: form.produceMaterialList.map((el: any) => ({
      craftTaskClientNo: el.craftTaskClientNo, // 生产工艺任务前端唯一识别码
      stockGoodsCode: el.stockGoodsCode, // 库存物料代码
      planUseQuantity: el.planUseQuantity, // 计划用料数量
      printMaterialQuantity: el.printMaterialQuantity, // 打印用料数量
      materialRemark: el.produceMaterialRemark // 物料备注
    })),
    colorMachines: form.colorMachineList.map((el: any) => ({
      produceTaskBillNo: el.produceTaskBillNo,// 生产单编号
      printColorCode: el.printColorCode,// 颜色编号
      machineCode: el.machineCode,// 机台编号
    }))
  }
  proxy.$api.ProductionBusniess.ExcuteUpdateProduceTaskBill(_form)
    .then((res: any) => {
      if (isConfirm) {
        proxy.$api.ProductionBusniess.SureProduceTaskBill({
          produceTaskID: _form.produceTaskID,
        })
          .then((res: any) => {
            _sun()
          })
          .catch(() => { });
      } else {
        _sun()
      }
    })
    .catch(() => { });
  function _sun() {
    proxy.$message('保存成功')
    sendMsg('save', true);
    // getForm();
    window.close();
  }
};
const setLoading = (title: string = '正在获取数据,请稍等...') => {
  if (!data.loading) {
    data.loading = true;
    data.loadingMsg = title;
  }
};
import { getMachine, getProduceCraft } from '@/utils/optionsArr.ts';
onMounted(() => {
  getForm();
  getMachine(options, 'machine') //获取设备
  getProduceCraft(options, 'produceCraft') //获取工艺数据
});
</script>
